﻿using System;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using Ah.Testudin.Engine.Actors;
using Ah.Testudin.Engine.Events;

namespace Ah.Testudin.Engine.Graphics.Scenes.SceneNodes
{
    public class ModelSceneNode : SceneNodeBase
    {
        #region Private Member Variables

        private readonly Model _model;

        #endregion

        public ModelSceneNode(
            ActorId actorId,
            RenderPass renderPass,
            Matrix toWorldTransform,
            Model model,
            IEventManager eventManager)
            : base("Model", actorId, renderPass, toWorldTransform)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            _model = model;
        }

        #region SceneNodeBase

        public override void Render(Scene scene)
        {
            scene.Renderer.BlendState = BlendState.Opaque;
            scene.Renderer.DepthStencilState = DepthStencilState.Default;

            Matrix[] meshTransforms = new Matrix[_model.Bones.Count];

            _model.CopyAbsoluteBoneTransformsTo(meshTransforms);

            foreach (ModelMesh currentMesh in _model.Meshes)
            {
                Matrix currentMeshTransform = meshTransforms[currentMesh.ParentBone.Index];

                foreach (BasicEffect currentEffect in currentMesh.Effects)
                {
                    currentEffect.World =
                        currentMeshTransform *
                        this.Properties.ToWorldTransform;

                    currentEffect.View = scene.Camera.View;

                    currentEffect.Projection = scene.Camera.Projection;

                    currentEffect.EnableDefaultLighting();
                }

                currentMesh.Draw();
            }
        }

        #endregion
    }
}
